package com.woniuxy.realm;
/*
 * @author 幸琦林
 *
 */

import com.woniuxy.configuration.EasyTypeToken;
import com.woniuxy.entity.SysAuthority;
import com.woniuxy.entity.SysRole;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//      需要在此处提供当前账户角色、权限的信息
        //1.通过账号找到uid，通过hid做连表查询找到所以的角色
        User user = (User) principals.getPrimaryPrincipal();
        //循环将用户的角色信息放入到set中,用户角色
        Set<String> roles = new HashSet<>();

        //从数据库中查询出了权限信息
        Set<String> perms = new HashSet<>();
        for (SysRole role : user.getRoles()) {
        	System.out.println("角色信息："+role.getNameRole());
            roles.add(role.getNameRole());
            for (SysAuthority userPerm : userService.findUserPerms(role.getIdRole())) {
                perms.add(userPerm.getNameAuth());
            }
        }

//        该用户的所有角色信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        //将这些角色的权限信息放入到info中
        info.addStringPermissions(perms);
        System.out.println("userRealm/doGetAuthorizationInfo:添加权限");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SimpleAuthenticationInfo info = null;
        String account = (String) token.getPrincipal();
        User user = userService.userLogin(account);
        System.out.println("shiro/realm:" + user);
        if (user != null) {
            info = new SimpleAuthenticationInfo(user, user.getPwd(), getName());
        }
        return info;
    }
}
